﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Songhay.OpenXml
{
    using Songhay.OpenXml;

    /// <summary>
    /// Static members for Open XML.
    /// </summary>
    public static partial class OpenXmlUtility
    {
        /// <summary>
        /// Loads the “flat OPC” document
        /// and returns a <c>w:document</c> element.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns>
        ///     Returns a <c>w:document</c>
        ///     <see cref="System.Xml.Linq.XElement"/>.
        /// </returns>
        public static XElement LoadFlatDocument(string uri)
        {
            var xd = XDocument.Load(uri);
            var parts = xd.Root
                .Elements(OpenXmlUtility.NamespaceXmlPackage + "part");
            var docPart = parts
                .Where(e => (string)e.Attribute(
                    OpenXmlUtility
                        .NamespaceXmlPackage + "name") ==
                        "/word/document.xml");
            var xmlData = docPart
                .Elements(OpenXmlUtility.NamespaceXmlPackage + "xmlData")
                .FirstOrDefault();
            var document = xmlData
                .Element(SonghayW.document);
            return document;
        }
    }
}
